'use strict'

import { app, protocol, BrowserWindow, ipcMain, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
import { Menu } from 'electron'

// const windowStateKeeper = require('electron-window-state');
let newWindow
let nexWin
let newPei
let childWindows = []
let newPeist

const isDevelopment = process.env.NODE_ENV !== 'production'

const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:8080` // 端口号根据个人项目进行更改
  : `file://${__dirname}/index.html`
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
app.allowRendererProcessReuse = false;

async function createWindow() {
  // Create the browser window.
  Menu.setApplicationMenu(null)
  const win = new BrowserWindow({
    width: 485,
    height: 344,
    title: '交换机路由器数据集成分析系统',
    closable: true,
    resizable: false,//禁止窗口随意拉伸
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      backgroundThrottling: false,//窗口最小化代码仍然执行
      enableRemoteModule: true,//控制窗口最小化
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
    

    Menu.on('closed', () => {
      childWindows.forEach(childWindow => {
        childWindow.close();
      });
      Menu = null
    })
  }
}
// 纠错窗口
function jiuCuo() {
  ipcMain.on('create-new-window', () => {
    if (newWindow) {
      newWindow.focus() // 存在 则聚焦
      return
    }
    newWindow = new BrowserWindow({
      width: 1107,
      height: 603,
      title: '交换机路由器数据集成分析系统-纠错',
      closable: true,
      resizable: false,//禁止窗口随意拉伸
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true,
        devTools:false
      }
    })
    newWindow.loadURL(winURL + '#/about')
    newWindow.on('closed', () => {
      newWindow = null
    })
  })
}
// 纠错展示窗口
function zhanShi() {
  ipcMain.on('create-new', (event,newValue) => {
    console.log(newValue);
    if (nexWin) {
      nexWin.focus() // 存在 则聚焦
      return
    }
    nexWin = new BrowserWindow({
      width: 600,
      height: 500,
      title: '交换机路由器数据集成分析系统-纠错展示',
      closable: true,
      resizable: false,//禁止窗口随意拉伸
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true,
        devTools:false
      }
    })
    nexWin.loadURL(winURL + '#/other')
    nexWin.on('closed', () => {
      nexWin = null
    })
    nexWin.webContents.on('did-finish-load',()=>{
      const windows = BrowserWindow.getAllWindows()
      windows.forEach(win => {
          win.webContents.send('message-from-kiss', newValue)
      })
    })
  })
}
// 注释窗口
function zhuShi() {
  ipcMain.on('create-zhu', (event, newValue) => {
    // 发送消息到渲染进程
    const win = BrowserWindow.getAllWindows().find(win => win.isAlwaysOnTop())
    if (win) {
      win.webContents.send('print-message', newValue)
    }
    const { width } = screen.getPrimaryDisplay().workAreaSize
    if (newPeist) {
      newPeist.focus() // 存在 则聚焦
      return
    }
    newPeist = new BrowserWindow({
      width: 300,
      height: 900,
      x: width - 300,
      y: 100,
      title: '注释展示',
      closable: true,
      transparent: true, // 设置窗口为透明
      opacity: 0.65,
      alwaysOnTop: true,
      minimizable: false,
      resizable: false,//禁止窗口随意拉伸
     
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true,
       
      }
    })
    newPeist.loadURL(winURL + '#/zhushi')
    newPeist.on('closed', () => {
      newPeist = null
    })
  })
}

// 培训窗口
function peiXun() {
  ipcMain.on('create-new-pei', (event,newValue) => {
    console.log(newValue);
    if (newPei) {
      newPei.focus() // 存在 则聚焦
      return
    }
    newPei = new BrowserWindow({
      width: 600,
      height: 500,
      title: '交换机路由器数据集成分析系统-培训',
      frame: true,//是否显示边缘框
      fullscreen: false, //是否全屏显示
      closable: true,
      resizable: false,//禁止窗口随意拉伸
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true,
        devTools:false
      }
    })
    newPei.loadURL(winURL + '#/peixun')                    
    newPei.on('closed', () => {
      newPei = null
    })
    newPei.webContents.on('did-finish-load',()=>{
      const windows = BrowserWindow.getAllWindows()
      windows.forEach(win => {
          win.webContents.send('message-from-main', newValue.data)
      })
    })

  })
}


// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS3_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
  jiuCuo()
  zhuShi()
  zhanShi()
  peiXun()
})

ipcMain.on('close-window',()=>{
  if(newPeist){
    newPeist.close()
  }
})

ipcMain.on('close-wtt',()=>{
  if(nexWin){
    nexWin.close()
  }
})



// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}



